package com.flow.framework.core.validation.validator;

import com.flow.framework.common.exception.ParamCheckedException;
import com.flow.framework.core.validation.annotation.MaxDecimalCustomization;
import com.flow.framework.core.validation.validator.base.BaseValidator;

import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;

/**
 * DecimalMax校验器
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/22
 */
public class MaxDecimalValidator extends BaseValidator<MaxDecimalCustomization, BigDecimal> {

    private MaxDecimalCustomization maxDecimalCustomization;

    private String errorMsg;

    @Override
    public void initialize(MaxDecimalCustomization maxDecimalCustomization) {
        this.maxDecimalCustomization = maxDecimalCustomization;
        this.errorMsg = "value greater than" + maxDecimalCustomization.value();
    }

    @Override
    public boolean isValid(BigDecimal value, ConstraintValidatorContext context) {
        if (null == value) {
            return true;
        }

        if (maxDecimalCustomization.containsEquals()) {
            if (value.compareTo(new BigDecimal(maxDecimalCustomization.value())) > 0) {
                super.logError(context, value, errorMsg);
                throw new ParamCheckedException(maxDecimalCustomization.errorCode());
            }
        } else {
            if (value.compareTo(new BigDecimal(maxDecimalCustomization.value())) >= 0) {
                super.logError(context, value, errorMsg);
                throw new ParamCheckedException(maxDecimalCustomization.errorCode());
            }
        }
        return true;
    }
}
